<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="default" @click="handleExport()">
          <Icon icon="i-ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <a-button type="default" @click="handleImport()">
          <Icon icon="i-ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button>
        <a-button type="default" @click="handleSyn({})" v-auth="'rd:db:transferorder:edit'">
          <Icon icon="i-simple-line-icons:refresh" /> {{ t('同步任务') }}
        </a-button>
        <a-button type="default" @click="handlePrint()" v-auth="'wms:rd:order:rdOrder:edit'">
          <Icon icon="ant-design:printer-twotone" /> {{ t('打印') }}
        </a-button>
        <Popconfirm placement="bottom" :title="t('是否确认撤销？')" @confirm="handleCancel">
          <a-button type="default" v-auth="'wh:rd02:rd02:edit'">
            <Icon icon="ant-design:code-outlined" /> {{ t('撤销') }}
          </a-button>
        </Popconfirm>
        <Popconfirm placement="bottom" :title="t('是否手动推送？')" @confirm="handlets">
          <a-button type="default" v-auth="'wh:rd01:rd01:edit'">
            <Icon icon="ant-design:check-outlined" /> {{ t('手动推送') }}
          </a-button>
        </Popconfirm>
        <a-button
          type="default"
          @click="handleGenerateTask({})"
          v-auth="'rd:db:transferorder:edit'"
        >
          <!-- <DownloadOutlined /> -->
          <Icon icon="i-ant-design:download-outlined" /> {{ t('生成下架任务') }}
        </a-button>
        <a-button type="success" ghost @click="handleForm({})" v-auth="'rd:db:transferorder:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id, sourceFlag: record.sourceFlag, bgen: record.bgen })">
          {{ record.fbillno }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <InputFormView @register="registerViewDrawer" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
    <BasicModal v-bind="$attrs" @register="registerModal" title="请确认拣货方式" @ok="handleQr">
      <BasicForm @register="registerForm" />
    </BasicModal>
    <PrintModal @register="registerPrintModal" />
  </div>
</template>
<script lang="ts" setup name="ViewsWmsRdDbTransferorderList">
  import { unref, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    transferorderDelete,
    transferorderListData,
    synTransferorder,
    generateTask,
    batchSend,
    transferorderRevoke,
  } from '/@/api/wms/rd/db/transferorder';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import InputFormView from './formView.vue';
  import FormImport from './formImport.vue';
  import { Popconfirm } from 'ant-design-vue';
  import PrintModal from '/@/components/print/printModal.vue';
  import { useUserStore } from '/@/store/modules/user';

  const { t } = useI18n('rd.db.transferorder');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  import { useConfig } from './config';
  const userStore = useUserStore();
  const { searchForm, tableColumns } = useConfig(t);

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('调拨管理'),
  };

  searchForm.schemas.forEach((schema) => {
    if (schema.field === 'companyCode' && schema.componentProps) {
      schema.componentProps.onChange = () => handleSuccess({} as Recordable);
    }
  });

  const actionColumn: BasicColumn = {
    width: 80,
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑调拨'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'rd:db:transferorder:edit',
        ifShow: () => {
          // 如果bgen 为1 则不能编辑
          return record.sourceFlag !== '0' && record.bgen !== '1';
        },
      },
      {
        icon: 'i-ant-design:delete-outlined',
        color: 'error',
        title: t('删除调拨'),
        popConfirm: {
          title: t('是否确认删除调拨'),
          confirm: handleDelete.bind(this, record),
        },
        auth: 'rd:db:transferorder:edit',
        ifShow: () => {
          return record.sourceFlag !== '0' && record.bgen !== '1';
        },
      },
    ],
  };

  onMounted(async () => {
    setProps();
    handleCompany();
  });

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerViewDrawer, { openDrawer: openViewDrawer }] = useDrawer();
  const [registerTable, { reload, getForm, getSelectRows, getSelectRowKeys, setProps }] = useTable({
    rowKey: 'id',
    api: transferorderListData,
    beforeFetch: (params) => {
      // params.busType = '0';
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleForm(record: Recordable) {
    // openDrawer(true, record);
    // bgen 为1 也是 openViewDrawer
    if (record.sourceFlag === '0' || record.bgen === '1') {
      openViewDrawer(true, record);
    } else {
      openDrawer(true, record);
    }
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/rd/db/transferorder/exportData',
      params: getForm().getFieldsValue(),
    });
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handleImport() {
    importModal(true, {});
  }

  async function handleDelete(record: Recordable) {
    const params = { id: record.id };
    const res = await transferorderDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  async function handleSyn() {
    const res = await synTransferorder({});
    showMessage(res.message);
    handleSuccess({});
  }
  const [registerForm, { validate }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: t('拣货方式'),
        field: 'type',
        component: 'Select',
        defaultValue: '1',
        componentProps: {
          dictType: 'jh_type',
          // allowClear: true,
        },
        required: true,
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });
  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();

  async function handleGenerateTask() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    openModal(true, {});
    // const selIds = arr.map((item) => item.id).join(',');
    // const params = { selIds: selIds };
    // const res = await generateTask(params);
    // console.log(res, 'res');
    // showMessage(res.message);
    // handleSuccess({});
  }

  async function handleQr() {
    try {
      let dataValidate = await validate();
      setModalProps({ confirmLoading: true });
      const jhPlanAreaList = getSelectRows();
      const ids = jhPlanAreaList.map((item) => item.id).join(',');
      const data: any = {
        ...dataValidate,
        selIds: ids,
      };
      const res = await generateTask(data);
      showMessage(res.message);
      reload();
      closeModal();
      // setTableData3([]);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  async function handlets() {
    if (getSelectRows().length) {
      let selIds = getSelectRows()
        .map((item) => item.id)
        .join(',');
      const res = await batchSend({ selIds });
      showMessage(res.message);
      handleSuccess({});
    } else {
      showMessage('请先选择数据');
    }
  }

  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  async function handlePrint() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length == 0) {
      showMessage(t('请先选择数据'));
      return;
    }
    // let newArr = arr.map(item=>{
    //   return item.djno
    // })
    let params = {
      ids: arr.join(','),
      title: '调拨单',
      height: '0.9',
      width: '0.9',
      fileName: '调拨单',
    };
    openPrintModal(true, params);
  }

  async function handleCancel() {
    const res = await transferorderRevoke({ id: getSelectRowKeys()[0] });
    showMessage(res.message);
    handleSuccess({});
  }

  async function handleCompany() {
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
    reload();
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
  }
</script>
